<template>
  <a-upload
    name="file"
    listType="picture-card"
    class="avatar-uploader"
    :showUploadList="false"
    action="https://file.suofeiyahome.com/upload"
    :data="{'fileType':'image'}"
    :headers="{'Accept':'application/json'}"
    :beforeUpload="beforeUpload"
    @change="handleChange">
    <a-avatar
      shape="square"
      v-if="imgUrl"
      :size="64"
      icon="user"
      :src="imgUrl"
      alt="avatar" />
    <div v-else>
      <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">上传</div>
    </div>
  </a-upload>
</template>
<script>
import { includes } from 'lodash'
export default {
  name: 'UploaderSingleImage',
  data () {
    return {
      uploadLoading: false,
      imgUrl: ''
    }
  },
  components: {

  },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    value: {
        type: String
    }
  },
  watch: {
    value (newVal) {
      this.imgUrl = newVal
    },
    imgUrl (newVal) {
      // this.$emit('input', newVal)
      // 向父组件更新
      this.$emit('change', newVal)
    }
  },
  methods: {
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      // console.log(info)
      if (info.file.status === 'done' && info.file.response.code === 0) {
        this.imgUrl = info.file.response.data.url
        this.uploadLoading = false
      }
    },
    beforeUpload (file) {
      const allowUploadTypeList = ['image/jpeg', 'image/png', 'image/gif']
      // const isJPG = file.type === 'image/jpeg';
      const isJPG = includes(allowUploadTypeList, file.type)
      if (!isJPG) {
        this.$message.error('必须上传图片类型为图片!')
      }

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小必须小于2M!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
